#ifndef LINEAR_H
#define LINEAR_H

#include <stdio.h>
#include <stdlib.h>

#include "util.h"

typedef struct
{
    ElemType data[MaxSize];
    int length;
} SqList; // Sequence List

typedef struct
{
    ElemType *data;
    int length, capacity;
} DSqList; // Dynamic Sequence List

int initDSqList(DSqList *DL)
{
    DL->data = (ElemType *)malloc(sizeof(ElemType) * InitSize);
    if (!DL->data)
        exit(OVERFLOW);
    DL->length = 0;
    DL->capacity = InitSize;
    return OK;
}

// O(n)
int ListInsert(SqList *L, int i, ElemType e)
{
    if (i < 1 || i > L->length + 1)
        return ERROR;
    if (L->length >= MaxSize)
        return ERROR;

    for (int j = L->length; j >= i; j--)
        L->data[j] = L->data[j - 1];

    L->data[i - 1] = e;
    L->length++;
    return OK;
}
// O(n)
int ListDelete(SqList *L, int i, ElemType *e)
{
    if (i < 1 || i > L->length)
        return ERROR;

    *e = L->data[i - 1];
    for (int j = i; j < L->length; j++)
        L->data[j - 1] = L->data[j];
    L->length--;
    return OK;
}
// O(1)
int GetElem(SqList *L, int i, ElemType *e)
{
    if (i < 1 || i > L->length)
        return ERROR;

    *e = L->data[i - 1];
    return OK;
}
// O(n)
int LocateElem(SqList *L, ElemType e)
{
    int i;
    for (i = 0; i < L->length; i++)
        if (L->data[i] == e)
            return i + 1;
    return 0;
}

// 动态分配的顺序表需要手动free
int DestroyList(DSqList *L)
{
    if (L->data)
        free(L->data);
    L->data = NULL;
    L->length = 0;
    L->capacity = 0;
    return 0;
}

int ClearList(SqList *L)
{
    L->length = 0;
    return OK;
}

int Empty(SqList *L)
{
    if (L->length == 0)
        return 1;
    else
        return 0;
}

void PrintList(SqList *L)
{
    for (int i = 0; i < L->length; i++)
    {
        printf("%d ", L->data[i]);
    }
    printf("\n");
}

#endif /* LINEAR_H */